/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2014 All Rights Reserved.
 */
package com.alipay.servlet.sscloud;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.constants.AlipayServiceEnvConstants;
import com.alipay.dispatcher.Dispatcher;
import com.alipay.executor.ActionExecutor;
import com.alipay.f2fpay.ToAlipayQrTradePay;
import com.alipay.factory.AlipayAPIClientFactory;
import com.alipay.util.LogUtil;
import com.alipay.util.RequestUtil;

/**
 * 开发者网关，支付宝所有主动和开发者的交互会经过此网关进入开发者系统
 * 
 * @author taixu.zqq
 * @version $Id: GatewayServlet.java, v 0.1 2014年7月22日 下午5:59:55 taixu.zqq Exp $
 */
public class AlipayTradeCancelServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1210436705188940602L;

    /** 
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
                                                                          IOException {
        this.doPost(req, resp);
    }

    /**
     * 网关处理
     * 
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                                                                                   throws ServletException,                                                                                  IOException {
        //支付宝响应消息  
        JSONObject json=new JSONObject();
        json.put("success", false);

        //1. 解析请求参数
        Map<String, String> params = RequestUtil.getRequestParams(request);    
    	String out_trade_no=params.get("out_trade_no"); //商户唯一订单号
       
        try {
        	AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient();
        	
        	AlipayTradeCancelRequest tradeCancelRequest = new AlipayTradeCancelRequest();
        	StringBuilder sb = new StringBuilder();
    		sb.append("{\"out_trade_no\":\"" + out_trade_no + "\",");
    		
    		System.out.println(sb.toString());
    		tradeCancelRequest.setBizContent(sb.toString());
        	//tradeQueryRequest.setBizContent("{\"out_trade_no\":\""+out_trade_no+"\"}");
    		AlipayTradeCancelResponse  tradeCancelResponse = alipayClient.execute(tradeCancelRequest);
        	if (null != tradeCancelResponse && tradeCancelResponse.isSuccess()) {		
        		 json.put("success", true);
        		 //交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
        		 json.put("code", tradeCancelResponse.getCode());
        		 json.put("sub_msg", tradeCancelResponse.getSubMsg());
        		 json.put("out_trade_no", tradeCancelResponse.getOutTradeNo());
        	}
        	
        } catch (Exception exception) {
           

        } finally {
            //5. 响应结果加签及返回
            try {
               
                //http 内容应答
                response.reset();
                response.setContentType("text/xml;charset=UTF-8");
                PrintWriter printWriter = response.getWriter();
                printWriter.print(json.toString());
                response.flushBuffer();

                //开发者自行决定是否要记录，视自己需求
                System.out.println("trade cancel responseMsg:"+json.toString());
                LogUtil.log("trade cancel responseMsg", json.toString());

            } catch (Exception alipayApiException) {
                //开发者可以根据异常自行进行处理
                alipayApiException.printStackTrace();
            }
        }
    }

    
	 

}
